package main

import (
	"os"

	"github.com/op/go-logging"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	port     = kingpin.Flag("port", "command string").Default(":22129").Short('p').String()
	auth     = kingpin.Flag("auth", "auth address string").Required().Short('a').String()
	pem      = kingpin.Flag("pem", "pem file").Short('e').Default("key.pem").String()
	key      = kingpin.Flag("key", "authorized keys").Short('k').Default("key.json").String()
	log_file = kingpin.Flag("log", "log ").Short('l').String()
	log      = logging.MustGetLogger("authclient")
	format   = logging.MustStringFormatter(
		`%{time:15:04:05.000} %{longfunc} %{level:.4s} %{id:03x} %{message}`,
	)
)

func main() {
	kingpin.Parse()

	var bk *logging.LogBackend

	if *log_file == "" {
		bk = logging.NewLogBackend(os.Stdout, "", 0)
	} else {
		file, err := os.OpenFile(*log_file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Errorf("open log file %s , error: ", *log_file, err)
		}
		defer file.Close()
		bk = logging.NewLogBackend(file, "", 0)
	}
	fmtbk := logging.NewBackendFormatter(bk, format)
	logging.SetBackend(fmtbk)

	srv, err := NewSshServer(*port, *pem, *key)
	if err != nil {
		log.Errorf("setup server error: %v", err)
		os.Exit(2)
	}
	if err = srv.serve(); err != nil {
		log.Errorf("setup server error: %v", err)
	}
}
